﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NModbus;

namespace EONFULLSIN.Views.Device
{
    /// <summary>
    /// 卓岚通信协议类
    /// </summary>
    public class ModbusZlanHelper
    {
        private static string ipAddress = "192.168.1.201";
        private static int port = 8801;

        private string data;
        NetworkStream stream;

        private void retry()
        {
            Trace.WriteLine("zlan retry..");
            getData();
        }

        public string getData()
        {
            try
            {
                Trace.WriteLine($"zlan connect..");
                using (var tcpClient = new TcpClient(ipAddress, port))
                {
                    stream = tcpClient.GetStream();

                    // Modbus TCP 查询报文
                    byte[] query =
                    {
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x06,
                    0x01,
                    0x03,
                    0x10,
                    0x00,
                    0x00,
                    0x08,
                };
                    // 发送查询报文
                    stream.Write(query, 0, query.Length);

                    // 接收响应
                    byte[] buffer = new byte[256];
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);
                    byte[] response = new byte[bytesRead];
                    Array.Copy(buffer, response, bytesRead);
                    data = BitConverter.ToString(response);
                  
                }
              
                
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"zlan Error: {ex.Message}");
                retry();
            }
            return data;
        }
    }
}
